﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoadPoolMembers.cs" company="">
//   
// </copyright>
// <summary>
//   Defines the LoadPoolsCommand type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace F5.BigIp.LocalTrafficManager.UI.Commands
{
    using System.ComponentModel;
    using System.Linq;

    using F5.BigIp.LocalTrafficManager.Interfaces;
    using F5.BigIp.LocalTrafficManager.UI.ViewModels;

    /// <summary>
    ///     The load pools command.
    /// </summary>
    public class LoadPoolMembers : BackgroundCommand
    {
        IPoolMemberService PoolMemberService { get; set; }

        #region Fields

        /// <summary>
        ///     The view model.
        /// </summary>
        private readonly MainViewModel viewModel;

        /// <summary>The pool.</summary>
        private IPool pool;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="LoadPoolMembers"/> class.</summary>
        /// <param name="viewModel">The view model.</param>
        /// <param name="poolMemberService"></param>
        public LoadPoolMembers(MainViewModel viewModel, IPoolMemberService poolMemberService)
        {
            this.viewModel = viewModel;

            this.PoolMemberService = poolMemberService;
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>The can execute.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public override bool CanExecute(object parameter)
        {
            this.pool = parameter as Pool;

            return this.pool != null &&
                   this.viewModel != null &&
                   this.PoolMemberService != null;
        }

        /// <summary>The do work.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected override void DoWork(object sender, DoWorkEventArgs e)
        {
            this.viewModel.IsBusy = true;

            this.viewModel.Timer.Stop();

            this.viewModel.PoolMembers = this.PoolMemberService.GetPoolMembers(this.pool).ToList();
        }

        /// <summary>The run worker completed.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected override void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.viewModel.IsBusy = false;

            this.viewModel.Timer.Start();
        }

        #endregion
    }
}